import pandas as pd
import openpyxl, re,sys
from io import BytesIO
from openpyxl.utils import get_column_letter
from collections import defaultdict
import tpl1,tpl2,tpl2,tpl3,tpl4,tpl5,tpl6,tpl0,tpl7
from pptx import Presentation
from pptx.util import Inches, Pt
import argparse

file_path = "123.xlsx"

parser = argparse.ArgumentParser(description="示例：python test.py --file_path=123.xlsx")

# 添加带参数名的参数
parser.add_argument('--file_path', type=str,  help='excel文件路径')

args = parser.parse_args()

if args.file_path:
    file_path = args.file_path
# ---------- 1. 读取工作簿 ----------
wb = openpyxl.load_workbook(file_path, data_only=True)
ws = wb.active
df = pd.read_excel(file_path, header=None, na_values=["", "NA", "NaN", "nan", None])

# ---------- 2. 提取图片为 BytesIO ----------
cell_img = {}                           # {"B7": BytesIO}
for img in ws._images:
    a = img.anchor._from
    coord = f"{get_column_letter(a.col)}{a.row}"
    cell_img[coord] = BytesIO(img._data())

# ---------- 3. 标题配置 ----------
def clean_title(s: str) -> str:
    # 去掉前缀数字序号（如 1.、4、、等）
    s = re.sub(r'^[\d\.\、\s]+', '', s)
    # 将 - 替换为一个空格
    s = s.replace('-', ' ')
    # 保留中文、英文、空格和括号
    return ''.join(re.findall(r'[A-Za-z\u4e00-\u9fa5 ()]+', s)).strip()

#tpl1 合并模板 表格+2行3列的图片
#tpl2 文字表格
#tpl4 方位图+top top_view
#tpl5 方位图 + top view + bottom view +...
#tpl6 行列转置图表
#tpl7 行列转置文字+图表

TITLES = {
    "批次信息": tpl1,
    "Test Data check": tpl2,
    "Online Check": tpl1,
    "Visual Inspection": tpl5,
    "IV Check": tpl6,
    "TDR Check": tpl6,
    "Check The FOL PR Position": tpl7,
    "CT Check": tpl6,
    "Remove VCM Check OIS Component": tpl4,
    "PP Measure": tpl6,
    "LIT Check":tpl6,
    "Cross section":tpl7,
    "Analysis": tpl0,
    "OS Check(By Multimeter)": tpl2,
}

# ---------- 4. 扫描整表并切块 ----------
result = {}           # {title: list(blocks)}
current = None        # 当前标题信息 dict
start_col = 0
def push_block():
    if not current: return
    blocks = result.setdefault(current["title"], [])
    for blk in current["buffer"]:
        blocks.append(blk)
    current["buffer"].clear()

rows, cols = df.shape

for r in range(rows):
    for c in range(cols):
        raw = df.iat[r, c]
        if isinstance(raw, str):
            t = clean_title(raw)
            if t in TITLES:   # ---- 标题单元格检测 ----
                push_block()  # 结束上一段
                current = {"title": t,
                           "mode": TITLES[t],
                           "start_row": r,
                           "start_col": c,
                           "buffer": []}
                #移除已存在的TITLES
                #TITLES.pop(t)
                continue

    # ------- 收集数据 -------
    if current:
        blk = []
        for cc in range(cols):
            #如果cc小于start_col，则跳过
            if cc < current["start_col"]:
                continue
            coord = f"{get_column_letter(cc)}{r}"
            val = cell_img.get(coord, df.iat[r, cc])
            if current['title'] == "Cross section":
                print(coord)
                print(val)
            blk.append(val)
        current["buffer"].append(blk)
push_block()

#如果列是Top View 则提取列图片排版
top_view_title = ["Visual Inspection","Remove VCM Check OIS Component"]
top_view_images = defaultdict()
for title,block in result.items():
    if title in top_view_title:
        #方向名称
        directionName = {}
        top_view = {}
        top_images = defaultdict(list)
        #按照列循环 #rIdx是数组下标 不是行列数
        for rIdx,row_data in enumerate(block):
            #跳过第一行和第二行 因为是标题
            if rIdx <= 1:
                continue
            #cIdx是数组下标 不是行列数
            for cIdx,col_data in enumerate(row_data):
                if cIdx == 0:
                    directionName[rIdx] = col_data
                    continue
                #如果不是图片则跳过
                if not isinstance(col_data, BytesIO):
                    continue
                top_images[cIdx].append({
                    directionName[rIdx]: col_data,
                 })
        result[title] = top_images

# === 4. 创建 PPT  ===
prs = Presentation()
prs.slide_width = Inches(13.33)
prs.slide_height = Inches(7.5)
#创建模块
for title,block in result.items():
    if title == "Analysis":
        continue
    module = TITLES[title]
    module.create_layout_ppt(prs, block,title)

# === 5. 保存输出 ===
output_path = "result.pptx"
prs.save(output_path)
print(f"✅")

